import {
  _decorator,
  CCInteger,
  Collider2D,
  Component,
  Contact2DType,
  Node,
  resources,
  Sprite,
  SpriteFrame,
  Vec3,
} from "cc"
const { ccclass, property } = _decorator

@ccclass("EnemyController")
export class EnemyController extends Component {
  // 移动速度
  @property({ type: CCInteger })
  speed: number = 50

  // 是否死亡
  isDie: boolean = false

  start() {
    // 注册碰撞
    let collider = this.getComponent(Collider2D)
    if (collider) {
      // tips：该项目只需要使用到最简单的碰撞系统Builtin 2D,文档中说，此碰撞系统只会产生两个事件回调
      // tips: BEGIN_CONTACT 和 END_CONTACT 回调消息
      collider.on(Contact2DType.BEGIN_CONTACT, this.contactBeginHandler, this)
    }
  }

  update(deltaTime: number) {
    if (!this.isDie) {
      let position = this.node.getPosition()
      position.y -= this.speed * deltaTime
      this.node.setPosition(new Vec3(position.x, position.y, 0))
      if (position.y < -820) {
        this.node.destroy()
      }
    }
  }
  /**
   * 死亡方法
   */
  die() {
    this.isDie = true
    // 先加载爆炸图片
    resources.load("airplane2/spriteFrame", SpriteFrame, (err, spriteFrame) => {
      if (!err) {
        this.node.getComponent(Sprite).spriteFrame = spriteFrame
      }
    })
    setTimeout(() => {
      this.node.destroy()
    }, 300)
  }
  // 和别人发生碰撞
  contactBeginHandler(info) {}
}
